<template>
  <div class="project-detail-container">
    <!-- 页面标题 -->
    <el-page-header @back="handleBack" content="项目详情编辑"></el-page-header>

    <!-- 主要内容区 -->
    <el-card class="project-form-card" shadow="always">
      <el-form ref="projectForm" :model="projectForm" :rules="rules" label-width="120px" class="project-form">
        <!-- 基础信息区域 -->
        <el-divider content-position="left">基础信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目标题" prop="title">
              <el-input v-model="projectForm.title" placeholder="请输入项目标题" maxlength="255"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="项目状态" prop="status">
              <el-select v-model="projectForm.status" placeholder="请选择项目状态">
                <el-option label="未启用" :value="0"></el-option>
                <el-option label="启用" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目标签" prop="tag">
              <el-input v-model="projectForm.tag" placeholder="请输入项目标签" maxlength="50"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="资源链接" prop="resourceUrl">
              <div class="resizable-input-container">
                <el-input v-model="projectForm.resourceUrl" placeholder="请输入资源链接" maxlength="255" type="textarea"
                  :rows="5" class="resizable-input" ref="resourceInput"></el-input>
                <div class="resize-handle" @mousedown="startResizing"></div>
              </div>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
          <el-form-item label="分类图标URL" prop="img">
           <image-upload v-model="projectForm.img" />
          </el-form-item>
            <el-form-item label="内容区域标题" prop="contentTitle">
              <el-input v-model="projectForm.contentTitle" placeholder="请输入内容区域标题" maxlength="255"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        


        <!-- 富文本编辑区域 -->
        <el-divider content-position="left">内容与介绍设置</el-divider>
        <el-form-item label="富文本内容">
          <editor v-model="projectForm.introDescription" :min-height="192" />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="form-actions">
          <el-button type="primary" @click="handleSubmit">
            保存
          </el-button>
          <el-button @click="handleCancel">
            取消
          </el-button>
          <el-button type="danger" @click="handleDelete" v-if="projectForm.id">
            删除
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getProject, addProject, updateProject, delProject } from '@/api/projectDetail/projectDetail'

export default {
  name: 'ProjectDetail',
  data() {
    return {
      // 项目表单数据（已改为驼峰命名）
      projectForm: {
        id: null,
        title: '',
        status: 0,
        richContent: '', // 富文本内容（与editor组件绑定）
        resourceUrl: '',
        createTime: '',
        updateTime: '',
        createBy: '',
        updateBy: '',
        tag: '',
        img: '',
        // 富文本拆分字段
        contentTitle: '',
        catalogTitle: '',
        introTitle: '',
        introDescription: '',
        introHighlight1: '',
        introMiddleText: '',
        introHighlight2: '',
        introEndText: ''
      },
      // 表单验证规则（已改为驼峰命名）
      rules: {
        title: [
          { required: true, message: '请输入项目标题', trigger: 'blur' },
          { max: 255, message: '项目标题不能超过255个字符', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择项目状态', trigger: 'change' }
        ],
        tag: [
          { max: 50, message: '项目标签不能超过50个字符', trigger: 'blur' }
        ],
        resourceUrl: [
          { max: 255, message: '资源链接不能超过255个字符', trigger: 'blur' }
        ],
        img: [
          { max: 255, message: '图片URL不能超过255个字符', trigger: 'blur' }
        ],
        richContent: [
          { required: true, message: '请输入富文本内容', trigger: 'blur' }
        ]
      },
      // 用于记录resize状态
      resizing: false,
      startY: 0,
      startHeight: 0
    }
  },
  created() {
    // 获取路由参数中的项目ID
    const projectId = this.$route.query.projectId;
    console.log('projectId:', projectId);
    if (projectId) {
      // 如果有ID，加载项目详情
      this.loadProjectDetail(projectId);
    }
  },
  methods: {
    
    // 加载项目详情
    loadProjectDetail(id) {
      console.log('loadProjectDetail:', id);
      getProject(id).then(response => {
        const data = response.data;
        console.log(data)
        // 构建富文本内容（已改为驼峰命名）
        

        // 合并其他字段
        this.projectForm = {
          ...this.projectForm,
          ...data,
          richContent: this.projectForm.richContent
        };
      }).catch(error => {
        console.error('加载项目详情失败:', error);
      });
    },

    // 提交表单
    handleSubmit() {
      this.$refs.projectForm.validate(valid => {
        if (valid) {
          // 准备提交的数据
          const submitData = { ...this.projectForm };


          // 判断是新增还是编辑
          if (submitData.id) {
            // 编辑操作
            updateProject(submitData).then(() => {
              this.$message.success('更新成功');
              this.$router.go(-1);
            }).catch(error => {
              this.$message.error('更新失败: ' + (error.message || '未知错误'));
            });
          } else {
            // 新增操作
            submitData.createBy = '当前登录用户';

            addProject(submitData).then(() => {
              this.$message.success('创建成功');
              this.$router.go(-1);
            }).catch(error => {
              this.$message.error('创建失败: ' + (error.message || '未知错误'));
            });
          }
        } else {
          this.$message.warning('请完善表单信息');
          return false;
        }
      });
    },

    // 取消操作
    handleCancel() {
      this.$router.go(-1);
    },

    // 返回操作
    handleBack() {
      this.$router.go(-1);
    },

    // 删除项目
    handleDelete() {
      this.$confirm('确定要删除这个项目吗？此操作不可撤销！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delProject(this.projectForm.id).then(() => {
          this.$message.success('删除成功');
          this.$router.push('/projects');
        }).catch(error => {
          console.error('删除项目失败:', error);
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 开始调整输入框大小
    startResizing(e) {
      this.resizing = true;
      this.startY = e.clientY;
      // 获取当前输入框高度
      this.startHeight = this.$refs.resourceInput.$el.clientHeight;
      
      // 绑定鼠标移动和释放事件
      document.addEventListener('mousemove', this.handleResizing);
      document.addEventListener('mouseup', this.stopResizing);
      
      // 防止默认行为
      e.preventDefault();
    },

    // 处理调整大小
    handleResizing(e) {
      if (!this.resizing) return;
      
      // 计算高度变化
      const deltaY = e.clientY - this.startY;
      const newHeight = this.startHeight + deltaY;
      
      // 设置最小高度限制
      if (newHeight >= 40) {
        this.$refs.resourceInput.$el.style.height = `${newHeight}px`;
        // 调整textarea高度
        const textarea = this.$refs.resourceInput.$el.querySelector('textarea');
        if (textarea) {
          textarea.style.height = `${newHeight}px`;
        }
      }
    },

    // 停止调整大小
    stopResizing() {
      this.resizing = false;
      // 移除事件监听
      document.removeEventListener('mousemove', this.handleResizing);
      document.removeEventListener('mouseup', this.stopResizing);
    }
  },
  // 组件销毁时确保移除事件监听
  beforeDestroy() {
    if (this.resizing) {
      document.removeEventListener('mousemove', this.handleResizing);
      document.removeEventListener('mouseup', this.stopResizing);
    }
  }
}
</script>

<style scoped>
.project-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.project-form-card {
  margin-top: 20px;
}

.project-form {
  margin-top: 20px;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

.form-actions .el-button {
  margin: 0 10px;
}

::v-deep .el-upload-list {
  margin-top: 10px;
}

.editor-toolbar {
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-bottom: none;
  background-color: #f5f7fa;
}

.editor-content {
  border: 1px solid #e4e7ed;
}

.editor {
  min-height: 300px;
  padding: 10px;
  outline: none;
}

::v-deep .el-divider--vertical {
  margin: 0 10px;
}

/* 可调整大小的输入框样式 */
.resizable-input-container {
  position: relative;
}

.resize-handle {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 6px;
  cursor: ns-resize;
  background-color: transparent;
}

.resize-handle:hover {
  background-color: rgba(0, 0, 0, 0.05);
}
</style>
